﻿using CSharpTestProject.Utils;
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace CSharpTestProject
{
    public partial class TeacherForm : Form
    {
        private _Sql sql;
        private string teacherName;
        public string TeacherName
        {
            set { teacherName = value; }
        }
        public TeacherForm()
        {
            InitializeComponent();
        }
        /*
         * TeacherForm加载完成
         * 链接数据库
         * 加载所有科目
         */
        private void TeacherForm_Load(object sender, EventArgs e)
        {
            sql = new _Sql();
            sql.SqlConnect();
            string sqlStr = $"SELECT DISTINCT kcm FROM students where teachr_name='{teacherName}'";
            DataSet coursesData = sql.SqlFind(sqlStr);
            int courseNum = coursesData.Tables[0].Rows.Count;
            string[] course = new string[courseNum];
            for (int i = 0; i < courseNum; i++)
            {
                course[i] = coursesData.Tables[0].Rows[i][0].ToString();
            }
            comboBox1.DataSource = course;
        }
        /*
         * 点名的单击事件函数
         * 从数据库中查找当前科目的所有人
         * 通过随机数算法去找到对应人数的学生，并展示在dataGridView里
         * 对于每个人都展示对话框，是否出勤，并将结果上传到数据库
         */
        private void button1_Click(object sender, EventArgs e)
        {
            string course = comboBox1.Text;
            if (course == "")
            {
                MessageBox.Show("请选择课程！");
                return;
            }
            if (comboBox2.Text == "")
            {
                MessageBox.Show("请选择人数！");
                return;
            }
            string query = $"SELECT * FROM students WHERE kcm='{course}' AND teachr_name='{teacherName}'";
            DataSet dataset = sql.SqlFind(query);
            int studentNum = dataset.Tables[0].Rows.Count;
            if (studentNum == 0)
            {
                MessageBox.Show("未查询到学生！");
                return;
            }
            Student[] students = new Student[studentNum];
            for (int i = 0; i < studentNum; i++)
            {
                students[i] = new Student(dataset.Tables[0].Rows[i][1].ToString(),
                    dataset.Tables[0].Rows[i][2].ToString(),
                    dataset.Tables[0].Rows[i][3].ToString());
            }
            int randomStudentNum = int.Parse(comboBox2.Text);
            if (randomStudentNum == 0)
                randomStudentNum = students.Length;
            if (randomStudentNum > studentNum)
            {
                randomStudentNum = studentNum;
                MessageBox.Show($"该班级有一共有{studentNum}名学生");
            }
            Student[] students2 = Utils.Utils.GetRandomStudents(students, randomStudentNum);
            // 填充数据到Dataset
            DataTable dt = new DataTable();
            //设置数据表格为只读
            dataGridView1.ReadOnly = true;
            //不允许添加行
            dataGridView1.AllowUserToAddRows = false;
            //背景为白色
            dataGridView1.BackgroundColor = Color.White;
            //只允许选中单行
            dataGridView1.MultiSelect = false;
            //整行选中
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            //平均分配列宽
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            // 展示在DataGridView上
            dataGridView1.DataSource = dt;
            dt.Columns.Add(new DataColumn("学号", typeof(string)));
            dt.Columns.Add(new DataColumn("姓名", typeof(string)));
            dt.Columns.Add(new DataColumn("班级", typeof(string)));
            dt.Columns.Add(new DataColumn("是否出勤", typeof(string)));
            DataRow row = dt.NewRow();
            for(int i = 0; i < randomStudentNum; i++)
            {
                row["学号"] = students2[i].Id;
                row["姓名"] = students2[i].Name;
                row["班级"] = students2[i]._Class;
                DialogResult dialogResult = MessageBox.Show(
                    $"班级：{students2[i]._Class}\n姓名：{students2[i].Name}\n学号：{students2[i].Id}\n是否出勤？",
                    "点名",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question);
                if (dialogResult == DialogResult.Yes)
                    row["是否出勤"] = "是";
                else
                    row["是否出勤"] = "否";
                dt.Rows.Add(row.ItemArray);
                string insert = $"INSERT INTO dmb (xh,name,sj,sfqq,kcm) VALUES('{students2[i].Id}','{students2[i].Name}','{DateTime.Now}','{row["是否出勤"]}','{course}')";
                try
                {
                    sql.ManageData(insert);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            

        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            var dgv = (DataGridView)sender;
            if (dgv.RowHeadersVisible)
            {
                Rectangle rectangle = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, e.RowBounds.Width, e.RowBounds.Height);
                rectangle.Inflate(-3, 0);
                TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, rectangle, e.InheritedRowStyle.ForeColor, TextFormatFlags.Left | TextFormatFlags.VerticalCenter);
            }
        }

        private void 点名记录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Record record = new Record();
            record.TeacherName = teacherName;
            record.Sql = sql;
            record.Show();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            comboBox1.Text = "";
            comboBox2.SelectedIndex = 0;
            dataGridView1.DataSource = null;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string course = comboBox1.Text;
            if (!string.IsNullOrEmpty(course))
            {
                string q = $"SELECT count(*) FROM students WHERE kcm='{course}' AND teachr_name='{teacherName}'";
                DataSet d = sql.SqlFind(q);
                int stuNum = int.Parse(d.Tables[0].Rows[0][0].ToString());
                string[] vs = new string[stuNum];
                for (int i = 0; i < stuNum; i++)
                {
                    vs[i] = (i+1).ToString();
                }
                comboBox2.DataSource = vs;
            }
        }
    }
}
